
#include "GeosphereVert.h"

// Need to do this outside of header to avoid cyclic dependency
#include "GeosphereFace.h"

#define PI_INV 0.31830988f
#define TWOPI_INV 0.15915494f

/*--------------------------------------------------------------------*/
GeosphereVert::GeosphereVert() {
	flag = false;
}

/*--------------------------------------------------------------------*/
void GeosphereVert::calcUnit() {
	unit = vert.normalized();
}

/*--------------------------------------------------------------------*/
void GeosphereVert::calcTexUV(Vec3f mid) {
	
	// Derived from:
	// http://www.cs.unc.edu/~rademach/xroads-RT/RTarticle.html#texturemap

	float phi = acos( -unit.y );
	texV = phi*PI_INV;

	float theta;
	if ( phi ) { 
		float inner = unit.x / sin(phi);
		inner = (inner>=1)?0.99999999f:(inner<=-1)?-0.99999999f:inner;
		theta = acos( inner ) * TWOPI_INV; 
	}
	else { theta = 0.5; }

	//texU = theta*0.5f;
	//texU += ( unit.z > 0 ) ? 0.0f : 0.5f;
	texU = (unit.z > 0) ? theta : 1-theta;

	// Fixing my special case, when the hemispheres come together
	if ( unit.z <= 0 && mid.z > 0 ) { texU = abs(1-texU); }
}

/*--------------------------------------------------------------------*/
void GeosphereVert::calcNorm() {			
	if ( adjFaces.empty() ) { norm = unit; return; }
	
	norm = Vec3f();

	list<GeosphereFace*>::iterator i;
	for ( i = adjFaces.begin() ; i != adjFaces.end() ; ++i ) {
		norm += *((*i)->getFaceNorm());
	}

	norm.normalize();
}
